package com.wangdao.mall.controller.admin;

import com.google.gson.Gson;
import com.wangdao.mall.model.Admin;
import com.wangdao.mall.model.Password;
import com.wangdao.mall.model.Result;
import com.wangdao.mall.service.AdminService;
import com.wangdao.mall.service.AdminServiceImp;
import com.wangdao.mall.utils.HttpUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * controller:控制单元、逻辑处理、校验
 * service:和每个功能点相关的代码
 * dao:查询数据
 * @Author:HaiyangTian
 * @Description:
 * @Date: Created in 15:42 2020/4/29
 * @Modified By:
 */
//第一个admin代表后端系统，第二个admin代表管理者模块
//  /*让管理者的登录和查询业务逻辑都传到这个servlet里来
@WebServlet("/api/admin/admin/*")
public class AdminServlet extends HttpServlet {

    //引用service层来处理业务逻辑
    private AdminService adminService = new AdminServiceImp();

    //把gson作为成员变量这样就可以全局都引用到
    Gson gson = new Gson();

    /**
     * 处理登陆等post业务逻辑
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //返回/api/admin/admin/login或者/api/admin/admin/allAdmins...
        String uri = request.getRequestURI();
        //将/api/admin/admin替换成空字符串。
        //这样就得到*处的我们需要处理的业务逻辑
        String action = uri.replace("/api/admin/admin/", "");
        //通过不同的action调用不同的方法完成不同的业务逻辑
        if ("login".equals(action)){
            login(request,response);
        }else if ("getSearchAdmins".equals(action)){
            getSearchAdmins(request,response);
        }else if ("addAdmins".equals(action)){
            addAdmins(request,response);
        }else if ("changePwd".equals(action)){
            changePwd(request,response);
        }else if ("updateAdmins".equals(action)){
            updateAdmins(request,response);
        }else if ("logoutAdmin".equals(action)){
            logoutAdmin(request,response);
        }
    }

    /**
     * 退出管理员登陆
     * @param request
     * @param response
     */
    private void logoutAdmin(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.getSession().invalidate();
        Result result = new Result();
        result.setCode(0);
        response.getWriter().println(gson.toJson(result));
    }

    /**
     * 修改管理员账户信息
     * @param request
     * @param response
     * @throws IOException
     */
    private void updateAdmins(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        Admin admin = gson.fromJson(requestBody, Admin.class);
        adminService.updateAdmins(admin);
        Result result = new Result();
        result.setCode(0);
        response.getWriter().println(gson.toJson(result));
    }

    /**
     * 修改管理员用户密码
     * @param request
     * @param response
     */
    private void changePwd(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //从请求体中获取修改的数据
        String requestBody = HttpUtils.getRequestBody(request);
        //将json转换成Password对象
        Password pwds = gson.fromJson(requestBody, Password.class);
        //进行一些校验
        Result result = new Result();
        if (pwds.getOldPwd().isEmpty() || pwds.getNewPwd().isEmpty() || pwds.getConfirmPwd().isEmpty()){
            result.setCode(10000);
            result.setMessage("密码不能为空，请重新输入");
            response.getWriter().println(gson.toJson(result));
            return;
        }else if (pwds.getOldPwd().equals(pwds.getNewPwd())){
            result.setCode(10000);
            result.setMessage("新密码不能与原密码相同,请重新输入");
            response.getWriter().println(gson.toJson(result));
            return;
        }else if (!pwds.getNewPwd().equals(pwds.getConfirmPwd())){
            result.setCode(10000);
            result.setMessage("两次密码输入不一致,请重新输入");
            response.getWriter().println(gson.toJson(result));
            return;
        }
        int row = adminService.changePwd(pwds,pwds.getAdminToken());
        if (row == 1){
            //修改成功
            result.setCode(0);
        }else {
            //修改错误
            result.setCode(10000);
            result.setMessage("原密码输入错误，请重新输入");
        }
        response.getWriter().println(gson.toJson(result));
    }

    /**
     * 添加管理员
     * @param request
     * @param response
     */
    private void addAdmins(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取请求体中的数据
        String requestBody = HttpUtils.getRequestBody(request);
        //将json转化成一个Admin对象
        Admin admin = gson.fromJson(requestBody, Admin.class);
        int row = adminService.addAdmins(admin);
        Result result = new Result();
        if (row == 1) {
            //添加成功
            result.setCode(0);
        } else {
            //添加失败
            result.setCode(10000);
            result.setMessage("账号或者昵称重复，添加管理员失败");
        }
        response.getWriter().println(gson.toJson(result));
    }

    /**
     * 搜索指定管理员用户
     * @param request
     * @param response
     */
    private void getSearchAdmins(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取请求体中的数据
        String requestBody = HttpUtils.getRequestBody(request);
        //将对应的数据封装到Admin对象中
        Admin params = gson.fromJson(requestBody, Admin.class);
        Result result = new Result();
        //进行校验
        if ("".equals(params.getNickname()) && "".equals(params.getEmail())){
            result.setCode(10000);
            result.setMessage("搜索内容不能全为空");
            response.getWriter().println(gson.toJson(result));
            return;
        }
        //返回一个查找集合
        List<Admin> admins = adminService.getSearchAdmins(params);
        result.setCode(0);
        result.setData(admins);
        response.getWriter().println(gson.toJson(result));
    }

    /**
     * 处理管理者登陆的业务逻辑
     * @param request
     * @param response
     */
    private void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //用gson转换将请求体中的参数转化为Admin对象
        //直接调用utils中的方法
        String requestBody = HttpUtils.getRequestBody(request);
        //将输出流中的数据转化为json字符串再转成Admin对象
        Admin admin = gson.fromJson(requestBody, Admin.class);
        //得到登陆状态的返回码
        int code = adminService.login(admin);
        Result result = new Result();
        if (code == 200){
            //返回正确的信息
            HttpSession session = request.getSession();
            session.setAttribute("email",admin.getEmail());
            Map<Object, Object> map = new HashMap<>();
            map.put("token",admin.getEmail());
            map.put("name",admin.getEmail());
            result.setCode(0);
            result.setData(map);
        }else{
            //返回错误的信息
            result.setCode(10000);
            result.setMessage("用户名或密码不正确，请重新输入");
        }
        //响应体的格式是json，所以转化为json返回
        response.getWriter().println(gson.toJson(result));
    }

    /**
     * 处理显示信息等get请求业务逻辑
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String uri = request.getRequestURI();
        String action = uri.replace("/api/admin/admin/", "");
        if ("allAdmins".equals(action)){
            allAdmins(request,response);
        }else if ("deleteAdmins".equals(action)){
            deleteAdmins(request,response);
        }else if ("getAdminsInfo".equals(action)){
            getAdminsInfo(request,response);
        }
    }

    /**
     * 得到待修改管理员用户的信息
     * @param request
     * @param response
     */
    private void getAdminsInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        Admin admin = adminService.getAdminsInfo(id);
        Result result = new Result();
        result.setCode(0);
        result.setData(admin);
        response.getWriter().println(gson.toJson(result));
    }

    /**
     * 删除管理员用户信息
     * @param request
     * @param response
     */
    private void deleteAdmins(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取请求体中的参数id
        String id = request.getParameter("id");
        int row = adminService.deleteAdmins(id);
        Result result = new Result();
        //校验
        if (row == 1) {
            result.setCode(0);
        } else {
            result.setCode(10000);
            result.setMessage("删除失败");
        }
        response.getWriter().println(gson.toJson(result));
    }

    /**
     * 展示所有的管理员信息
     * @param request
     * @param response
     */
    private void allAdmins(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<Admin> adminList = adminService.allAdmins();
        Result result = new Result();
        //校验
        if (!adminList.isEmpty()) {
            result.setCode(0);
            result.setData(adminList);
        } else {
            result.setCode(10000);
            result.setMessage("当前没有管理员用户，请添加");
        }
        response.getWriter().println(gson.toJson(result));
    }
}
